﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Controls;
using Pfz.DataTypes;
using Pfz.Factoring;

namespace Pfz.WpfControls.ValueControls
{
	/// <summary>
	/// Control used to get passwords with confirmation.
	/// </summary>
	[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
	[AutoRegisterInControlFactory(typeof(PasswordString))]
	internal sealed class PasswordControl:
		UserControl,
		IValueControl
	{
		private PasswordBox _password1;
		private PasswordBox _password2;
		
		/// <summary>
		/// Creates a new password control.
		/// </summary>
		public PasswordControl()
		{
			_password1 = new PasswordBox();
			_password2 = new PasswordBox();
		
			var stackPanel = new StackPanel();
			stackPanel.Children.Add(_password1);
			stackPanel.Children.Add(_password2);
			Content = stackPanel;
		}

		/// <summary>
		/// Clears both password boxes.
		/// </summary>
		public void Clear()
		{
			_password1.Clear();
			_password2.Clear();
		}

		/// <summary>
		/// Gets or sets a value telling that this control is read-only.
		/// </summary>
		public bool IsReadOnly
		{
			get
			{
				return !IsEnabled;
			}
			set
			{
				IsEnabled = !value;
			}
		}
		
		/// <summary>
		/// Gets or sets the password of the password boxes.
		/// Note that an exception is thrown if the values are different.
		/// </summary>
		[SuppressMessage("Microsoft.Performance", "CA1820:TestForEmptyStringsUsingStringLength")]
		public string Value
		{
			get
			{
				string text = _password1.Password;
				if (text != _password2.Password)
					throw new ArgumentException("Password and confirmation must match!");
					
				if (text == "")
					return null;
				
				return text;
			}
			set
			{
				_password1.Password = value;
				_password2.Password = value;
			}
		}

		#region IValueContainer Members
			object IValueContainer.Value
			{
				get
				{
					return new PasswordString(Value);
				}
				set
				{
					PasswordString str = (PasswordString)value;
					Value = str.ToString();
				}
			}
		#endregion
	}
}
